import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTokentime } from '@/utils/auth'
import router from '@/router'
// 登录时长
const timekey = 60*60*1000

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // 登录时间
      let logintime = getTokentime()
      // 现在时间
      let currenttime = Date.now()
      if ((logintime+timekey) < currenttime) {
        // 登出
        store.dispatch('user/logout')
        router.push('/login')
        Message({
          message: 'token超时，请重新登录！',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error('token超时了'))
      }
    config.headers.Authorization = `Bearer ${store.getters.token}`
    }
  return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(

  response => {
    const res = response.data
    // if(!res.success) {
    //   Message({
    //     message: response.massage,
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //   return Promise.reject(new Error(res.massage))
    // }
    return res
  },
  error => {
    // console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return error.message
    // return Promise.reject(error)
  }
)

export default service
